<template>
  <div v-loading="tableLoading" class="app-container">
    <div class="search-box">
      <el-form ref="searchForm" :inline="true" :model="formFilter">
        <el-form-item prop="name">
          <el-input v-model="formFilter.name" placeholder="姓名" style="width:160px;" />
        </el-form-item>
        <el-form-item prop="departmentId">
          <select-tree v-model="formFilter.departmentId" :options="deptIdOptions" width="200" clearable placeholder="所属部门" />
        </el-form-item>

        <el-form-item label="账号状态" prop="status">
          <el-select v-model="formFilter.status" style="width:100px;">
            <el-option label="全部" value="" />
            <el-option label="正常" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位状态" prop="state">
          <el-select v-model="formFilter.state" autocomplete="off" style="width:100px;">
            <el-option
              v-for="item in stateOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
          <el-button icon="el-icon-remove-outline" title="重置" @click="resetSearchForm" />
        </el-form-item>
      </el-form>
      <div class="toolbar-box clearfix">
        <el-button v-permission="['user:add']" type="primary" icon="el-icon-circle-plus" @click="add">新增</el-button>
        <el-button type="success" icon="el-icon-download" style="margin-right:10px;" @click="expexcel">导出</el-button>
        <el-dropdown>
          <el-button type="info">
            导入<i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-loading="downloadLoading" @click.native="downloadTpl()">下载导入模板</el-dropdown-item>
            <el-dropdown-item @click.native="impExcel()">导入用户</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-popover
          width="300"
          trigger="click"
          style="float: right;"
        >
          <div class="filter-columns">
            <el-checkbox-group v-model="selectedColumns">
              <el-checkbox label="sex">性别</el-checkbox>
              <el-checkbox label="jionday">入职日期</el-checkbox>
              <el-checkbox label="birthday">出生日期</el-checkbox>
              <el-checkbox label="idNo">身份证号</el-checkbox>
              <el-checkbox label="eduLevel">最高学历</el-checkbox>
              <el-checkbox label="gradeSchool">毕业院校</el-checkbox>
              <el-checkbox label="gradeDay">毕业时间</el-checkbox>
              <el-checkbox label="telephone">联系电话</el-checkbox>
              <el-checkbox label="mobile">手机号码</el-checkbox>
              <el-checkbox label="address">居住地址</el-checkbox>
              <el-checkbox label="email">Email</el-checkbox>
              <el-checkbox label="qq">QQ号</el-checkbox>
              <el-checkbox label="isSystem">系统用户</el-checkbox>
            </el-checkbox-group>
          </div>
          <el-button slot="reference">更多列... <i class="el-icon-arrow-down" /></el-button>
        </el-popover>

      </div>
    </div>

    <el-table
      ref="multipleTable"
      stripe
      :data="tableData"
      border
      class="table"
      @sort-change="sortChange"
    >
      <el-table-column prop="loginName" sortable="custom" label="账号" width="120" />
      <el-table-column prop="name" sortable="custom" label="姓名" width="120" />
      <el-table-column v-if="showColumn('jionday')" prop="jionday" label="入职日期">
        <template slot-scope="scope">
          <span>{{ scope.row.jionday | parseTime("{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="departmentName" sortable="custom" label="所属部门" />
      <el-table-column prop="positions" label="岗位">
        <template slot-scope="scope">
          <span>{{ scope.row.positions | namesFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="duty" label="职务" />
      <el-table-column prop="roles" label="拥有角色">
        <template slot-scope="scope">
          <span>{{ scope.row.roles | namesFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="locked" label="锁定" sortable="custom" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.locked |booleanFormat }}</span>
          <el-button
            v-if="scope.row.locked==1 && scope.row.status==1"
            type="text"
            icon="el-icon-key"
            class="ml-5 orange inline-btn"
            @click="unLock(scope.row.id, scope.row)"
          >解锁</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="职位状态" sortable="custom" width="110">
        <template slot-scope="scope">
          <span>{{ scope.row.stateName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="账号状态" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.status | statusFormat }}</span>
        </template>
      </el-table-column>

      <el-table-column v-if="showColumn('sex')" prop="sex" label="性别">
        <template slot-scope="scope">
          <span>{{ scope.row.sex| sexFormat() }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showColumn('birthday')" prop="birthday" label="出生日期">
        <template slot-scope="scope">
          <span>{{ scope.row.birthday | parseTime("{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showColumn('idNo')" prop="idNo" label="身份证号" />
      <el-table-column v-if="showColumn('eduLevel')" prop="eduLevel" label="学历" />
      <el-table-column v-if="showColumn('gradeSchool')" prop="gradeSchool" label="毕业院校" />
      <el-table-column v-if="showColumn('gradeDay')" prop="gradeDay" label="毕业日期">
        <template slot-scope="scope">
          <span>{{ scope.row.gradeDay | parseTime("{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showColumn('telephone')" prop="telephone" label="联系电话" />
      <el-table-column v-if="showColumn('mobile')" prop="mobile" label="手机号码" />
      <el-table-column v-if="showColumn('address')" prop="address" label="居住地址" />
      <el-table-column v-if="showColumn('qq')" prop="qq" label="QQ号" />
      <el-table-column v-if="showColumn('email')" prop="email" label="Email" />

      <el-table-column v-if="showColumn('createTime')" prop="createTime" label="创建日期">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | parseTime("{y}-{m}-{d} {h}:{i}") }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showColumn('isSystem')" prop="isSystem" label="系统用户">
        <template slot-scope="scope">
          <span>{{ scope.row.isSystem |booleanFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checkPermission(['user:edit'])" label="操作" width="190" align="left">
        <template slot-scope="scope">
          <el-button v-if="!scope.row.isSystem" type="text" icon="el-icon-edit" class="inline-btn" @click="handleEdit(scope.row.id)">编辑</el-button>
          <el-button
            v-if="!scope.row.isSystem && scope.row.status==1"
            type="text"
            icon="el-icon-delete"
            class="red inline-btn"
            @click="handleDelete(scope.row.id,scope.row)"
          >停用</el-button>
          <el-button
            v-if="!scope.row.isSystem && scope.row.status==0"
            type="text"
            icon="el-icon-star-on"
            class="green  inline-btn"
            @click="handleStart(scope.row.id, scope.row)"
          >启用</el-button>
          <el-button
            v-if="!scope.row.isSystem && scope.row.state==1"
            type="text"
            class="orange  inline-btn"
            @click="handleLeave(scope.row.id, scope.row)"
          >离职</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="curPage" :limit.sync="limit" @pagination="getList" />
    <uploadForm ref="uploadForm" />
  </div>
</template>

<script>
import request from '@/utils/request'
import Pagination from '@/components/Pagination'
import checkPermission from '@/utils/permission'
import { kebabCase } from '@/utils'
import SelectTree from '@/components/SelectTree'
import { getDeptTree } from '@/api/basedata'
import uploadForm from '../impresult/uploadForm'
import { downloadFile } from '@/utils'
export default {
  name: 'UserList',
  components: { Pagination, SelectTree, uploadForm },
  data() {
    return {
      stateOptions: [{ id: null, name: '全部' }, { id: 1, name: '在职' }, { id: 0, name: '离职' }],
      stationOptions: [],
      orderByClause: null,
      tableLoading: false,
      downloadLoading: false,
      tableData: [],
      curPage: 1,
      limit: 5,
      total: 0,
      formFilter: {
        state: 1,
        status: '1',
        departmentId: '',
        name: null
      },
      selectedColumns: []
    }
  },
  computed: {
    deptIdOptions() {
      return getDeptTree()
    }
  },
  created() {
    this.getList()
  },
  activated() {
    this.getList()
  },
  methods: {
    checkPermission,
    showColumn(column) {
      for (let j = 0, len = this.selectedColumns.length; j < len; j++) {
        if (column === this.selectedColumns[j]) {
          return true
        }
      }
      return false
    },
    // 获取数据
    getList() {
      this.tableLoading = true
      const param = {}
      const queryPage = {}
      queryPage.limit = this.limit
      queryPage.offset = this.limit * (this.curPage - 1)
      param.page = queryPage
      if (this.orderByClause && this.orderByClause.trim() !== '') {
        param.orderByClause = this.orderByClause
      }
      request({ url: '/sys/user/findPage', method: 'post', data: param })
        .then(res => {
          this.tableLoading = false
          this.tableData = res.rows
          this.total = res.total
          this.curPage = res.pageNumber
        })
        .catch(e => {
          this.tableLoading = false
          this.$message.error('查询出错')
        })
    },

    onSearch() {
      this.getList()
    },
    resetSearchForm() {
      this.$refs['searchForm'].resetFields()
    },
    handleEdit(id) {
      return this.$router.push({ path: '/sys/useredit/' + id })
    },
    handleDelete(id, row) {
      this.$confirm('此操作将停用用户[' + row.name + '], 是否继续?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDelete(id)
        })
    },
    doDelete(id) {
      this.tableLoading = true
      request({ url: '/sys/user/disable', method: 'get', params: { 'id': id }})
        .then(res => {
          this.tableLoading = false
          this.getList()
        })
        .catch(e => {
          this.tableLoading = false
          this.$message.error('停用出错！' + e.message ? e.message : '')
        })
    },
    handleStart(id, row) {
      this.$confirm('此操作将启用[' + row.name + '], 是否继续?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doStart(id)
        })
    },
    doStart(id) {
      this.tableLoading = true
      request({ url: '/sys/user/enable', method: 'get', params: { 'id': id }})
        .then(res => {
          this.tableLoading = false
          this.getList()
        })
        .catch(e => {
          this.tableLoading = false
          this.$message.error('启用出错！' + e.message ? e.message : '')
        })
    },
    handleLeave(id, row) {
      this.$confirm('此操作将用户[' + row.name + ']设为‘离职’, 是否继续?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doLeave(id)
        })
    },
    doLeave(id) {
      this.tableLoading = true
      request({ url: '/sys/user/leave', method: 'get', params: { 'id': id }})
        .then(res => {
          this.tableLoading = false
          this.getList()
        })
        .catch(e => {
          this.tableLoading = false
          this.$message.error('设为‘离职’出错！' + e.message ? e.message : '')
        })
    },
    unLock(id, row) {
      this.$confirm('此操作将解锁用户[' + row.name + '], 是否继续?', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doUnLock(id)
        })
    },
    doUnLock(id) {
      this.tableLoading = true
      request({ url: '/sys/user/unLocked', method: 'get', params: { 'id': id }})
        .then(res => {
          this.tableLoading = false
          this.getList()
        })
        .catch(e => {
          this.tableLoading = false
          this.$message.error('解锁出错！' + e.message ? e.message : '')
        })
    },
    add() {
      return this.$router.push({ path: '/sys/useradd' })
    },
    sortChange(param) {
      if (param.prop === 'departmentName') {
        this.orderByClause = 'department_id'
      } else {
        this.orderByClause = kebabCase(param.prop)
      }
      if (param.order === 'ascending') {
        this.orderByClause += ' asc'
      } else {
        this.orderByClause += ' desc'
      }
      this.getList()
    },
    expexcel() {
      const param = {}
      if (this.orderByClause && this.orderByClause.trim() !== '') {
        param.orderByClause = this.orderByClause
      }
      this.downloadLoading = true
      request({ url: '/sys/user/export', method: 'post', data: param, responseType: 'blob' })
        .then(data => {
          downloadFile(data, '用户', 'xlsx')
          this.downloadLoading = false
        })
        .catch(e => {
          this.downloadLoading = false
          this.$message.error('导出出错')
        })
    },
    downloadTpl() {
      this.loading = true
      request({ url: '/sys/user/exportTpl', method: 'get', responseType: 'blob' })
        .then(data => {
          downloadFile(data, '用户导入模板', 'xlsx')
          this.loading = false
        })
        .catch(e => {
          this.loading = false
          this.$message.error('下载导入模板出错')
        })
    },
    impExcel() {
      this.$refs.uploadForm.show('/sys/user/importExcel')
    }
  }
}
</script>
